package org.gl.training.gwt.client.view;

import java.util.ArrayList;
import java.util.List;

import org.gl.training.gwt.client.SessionManager;
import org.gl.training.gwt.client.service.UserService;
import org.gl.training.gwt.client.service.UserServiceAsync;
import org.gl.training.gwt.client.utils.MyAsyncCallback;
import org.gl.training.gwt.shared.model.UserVO;
import org.gl.training.gwt.shared.utils.RecordUtils;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.Cursor;
import com.smartgwt.client.types.ImageStyle;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.HStack;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.layout.VLayout;

public class AdminView extends HLayout {

	private ListGrid userGrid;

	private UserServiceAsync userServiceAsync = GWT.create(UserService.class);

	public AdminView() {
		setWidth100();
		setHeight100();

		VLayout mainLayout = new VLayout();
		mainLayout.setBorder("1px solid #629efa");
		mainLayout.setWidth(700);
		mainLayout.setHeight100();

		setMembers(new LayoutSpacer(), mainLayout, new LayoutSpacer());

		mainLayout.addMember(new HeaderView());

		VLayout body = new VLayout(10);
		body.setMargin(10);
		body.setWidth100();
		body.setHeight100();

		mainLayout.addMember(body);
		mainLayout.addMember(new FooterView());

		// Init body
		UserVO currentUserVO = SessionManager.getCurrentUserVO();
		Label labelUser = new Label(currentUserVO.getFullName());
		labelUser.setStyleName("header-text");
		labelUser.setWrap(false);

		Img infoImg = new Img("info.jpg");
		infoImg.setImageWidth(24);
		infoImg.setImageHeight(24);
		infoImg.setImageType(ImageStyle.NORMAL);
		infoImg.setCursor(Cursor.HAND);
		infoImg.addClickHandler(new InfoHandler());

		HStack currentUserLayout = new HStack(5);
		currentUserLayout.setWidth100();
		currentUserLayout.setHeight(24);
		currentUserLayout.addMember(labelUser);
		currentUserLayout.addMember(infoImg);

		body.addMember(currentUserLayout);

		userGrid = new ListGrid();
		userGrid.setWidth100();
		userGrid.setHeight100();
		userGrid.setShowAllRecords(true);
		userGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);
		userGrid.setSelectionType(SelectionStyle.SIMPLE);

		ListGridField nameField = new ListGridField("userName", "User Name");
		nameField.addRecordClickHandler(new RecordClickHandler());

		ListGridField fullNameField = new ListGridField("fullName", "Full Name");
		ListGridField emailField = new ListGridField("email", "E-mail");
		ListGridField userStatusField = new ListGridField("userStatus",
				"User Status");
		// ListGridField selectedField = new ListGridField("selected", " ");
		// selectedField.setType(ListGridFieldType.BOOLEAN);
		// selectedField.setCanEdit(true);
		userGrid.setFields(new ListGridField[] { nameField, fullNameField,
				emailField, userStatusField });

		body.addMember(userGrid);

		HLayout buttonsLayout = new HLayout();
		buttonsLayout.setMembersMargin(10);
		buttonsLayout.setWidth100();
		buttonsLayout.setHeight(24);

		Button emailButton = new Button("Email");
		emailButton.addClickHandler(new EmailHandler());
		Button approveButton = new Button("Approve");
		approveButton.addClickHandler(new ApproveHandler());
		Button deleteButton = new Button("Delete");
		deleteButton.addClickHandler(new DeleteHandler());

		buttonsLayout.addMember(emailButton);
		buttonsLayout.addMember(approveButton);
		buttonsLayout.addMember(deleteButton);
		buttonsLayout.setAlign(Alignment.RIGHT);

		body.addMember(buttonsLayout);

		loadListOfUsers();
	}

	protected void loadListOfUsers() {
		userServiceAsync.getUsers(new LoadUsersCallback());
	}

	protected List<Integer> getSelectedIds() {
		ListGridRecord[] selectedRecords = userGrid.getSelectedRecords();

		List<Integer> idList = new ArrayList<Integer>();

		for (ListGridRecord selectedRecord : selectedRecords) {
			Integer id = selectedRecord.getAttributeAsInt("id");
			idList.add(id);
		}
		return idList;
	}

	protected void setUserGridData(List<UserVO> userVOList) {
		List<ListGridRecord> userRecordList = RecordUtils
				.getUserGridRecords(userVOList);
		ListGridRecord[] userRecords = userRecordList
				.toArray(new ListGridRecord[userRecordList.size()]);
		userGrid.setData(userRecords);
	}

	private class RecordClickHandler implements
			com.smartgwt.client.widgets.grid.events.RecordClickHandler {

		@Override
		public void onRecordClick(RecordClickEvent event) {
			Integer userId = event.getRecord().getAttributeAsInt("id");
			String userFullName = event.getRecord().getAttributeAsString(
					"fullName");
			hide();

			DailyPlanView dailyPlanView = new DailyPlanView(userId);
			dailyPlanView.setDailyPlanOwnerText(userFullName);
			dailyPlanView.draw();
		}
	}

	private class SuccessCallback extends MyAsyncCallback<Void> {

		private String message;

		public SuccessCallback(String message) {
			super();
			this.message = message;
		}

		@Override
		public void onSuccess(Void result) {
			showSuccessMessage(message);
			loadListOfUsers();
		}

	}

	private class LoadUsersCallback extends MyAsyncCallback<List<UserVO>> {

		@Override
		public void onSuccess(List<UserVO> result) {
			setUserGridData(result);
		}
	}

	private class InfoHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			InfoView infoView = new InfoView(SessionManager.getCurrentUserVO()
					.getUserName());
			infoView.draw();

		}

	}

	private class EmailHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			List<Integer> idList = getSelectedIds();
			userServiceAsync.sendEmail(idList, new SuccessCallback(
					"Email(s) sent successfully"));
		}
	}

	private class ApproveHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			List<Integer> idList = getSelectedIds();
			userServiceAsync.approve(idList, new SuccessCallback(
					"User(s) approved successfully"));
		}
	}

	private class DeleteHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			List<Integer> idList = getSelectedIds();
			userServiceAsync.delete(idList, new SuccessCallback(
					"User(s) deleted successfully"));
		}
	}
}
